var config = require('../config/deafult');
var mongoose = require('mongoose');
var markdown = require('markdown').markdown;
var moment = require('moment');

mongoose.Promise=global.Promise;
mongoose.connect(config.mongodb,{useMongoClient:true});

//User
exports.User = mongoose.model('User', new mongoose.Schema({
    name: {
        type: String,
        index: true,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    avatar: {
        type: String,
        required: true
    },
    gender: {
        type: String,
        enum: ['m', 'f', 'x'],
        required: true
    },
    bio: {
        type: String
    },
    createTime: {
        type: Date,
        required: true
    }
}));


//Post
var PostSchema = new mongoose.Schema({
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    title: {
        type: String,
        index: true
    },
    content: String,
    pv: {
        type: Number,
        default: 0
    },
    createTime: {
        type: Date,
        required: true
    },
    commentsCount:{
        type:Number,
        default:0
    }
});
PostSchema.virtual('contentHTML').get(function () {
    return markdown.toHTML(this.content);
});
PostSchema.virtual('time').get(function () {
    return moment(this.createTime).format('YYYY-MM-DD HH:mm:ss');
});
exports.Post = mongoose.model('Post', PostSchema);

//Comment
var CommentSchema = new mongoose.Schema({
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    content: String,
    postId:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Post'
    },
    createdTime:Date
});
CommentSchema.virtual('contentHTML').get(function () {
    return markdown.toHTML(this.content);
});
exports.Comment = mongoose.model('Comment',CommentSchema);